/*
 * @Author: Wangjun
 * @Date: 2021-05-15 22:46:27
 * @LastEditTime: 2024-08-19 13:25:02
 * @LastEditors: wangjun haodreams@163.com
 * @Description:
 * @FilePath: \godriver\opdb\example\write\write.go
 * hnxr
 */
package main

import (
	"encoding/binary"
	"fmt"
	"log"
	"os"
	"strings"
	"time"

	"gitee.com/haodreams/godriver/opdb"
	"gitee.com/haodreams/godriver/opdb/opsql"
	"gitee.com/haodreams/golib/env"
	"gitee.com/haodreams/golib/logs"
	"gitee.com/haodreams/libs/ee"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

func main() {
	env.Reset()
	data, err := os.ReadFile("conf.txt")
	if err != nil {
		log.Fatalln(err)
	}

	ss := strings.Split(string(data), ";")
	dataSource := strings.TrimSpace(ss[0])

	dialector := opsql.Open(dataSource)
	if dialector == nil {
		ee.NewError("不支持的驱动:" + dataSource).Once2(logs.CbErrorf)
		return
	}
	op, err := gorm.Open(dialector, &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
	})

	if err != nil {
		log.Fatalln(err)
	}
	//查询服务器时间
	tm := ""
	err = op.Raw("SELECT time").First(&tm).Error
	if err != nil {
		log.Fatalln(err)
	}
	log.Println("服务器时间:", tm)

	if len(ss) < 2 {
		log.Fatalln("没有需要发送的数据")
	}

	ss = strings.Split(ss[1], ",")
	WriteReal(ss, op)
	WriteArchive(ss, op)
}

func WriteReal(names []string, op *gorm.DB) {
	var reals []*opdb.Binary
	var rows []interface{}

	for i := range names {
		real := new(opdb.Binary)
		real.Name = names[i]
		//real.Type = 6
		reals = append(reals, real)
		rows = append(rows, real)
	}

	//发送1000次
	t := time.Now().Unix()
	for i := 0; i < 1000; i++ {
		//t := time.Now().Unix()
		for j := 0; j < len(reals); j++ {
			//buf := make([]byte, 10)
			//binary.BigEndian.PutUint64(buf[2:], uint64(i))
			reals[j].Value = []byte(fmt.Sprintf("bin:%d", i))
			reals[j].Time = t + int64(i)
		}

		db, err := op.DB()
		if err != nil {
			logs.Error(err)
			return
		}
		_, err = db.Exec("Write Realtime", rows...)

		if err != nil {
			logs.Error(err)
			return
		}
		time.Sleep(time.Second)
	}
}

func WriteArchive(names []string, op *gorm.DB) {
	var reals []*opdb.Binary
	var rows []interface{}

	for i := range names {
		real := new(opdb.Binary)
		real.Name = names[i]
		reals = append(reals, real)
		rows = append(rows, real)
	}

	//发送1000次
	t := time.Now().Unix()
	for i := 0; i < 1000; i++ {
		//t := time.Now().Unix()
		for j := 0; j < len(reals); j++ {
			buf := make([]byte, 10)
			binary.BigEndian.PutUint64(buf[2:], uint64(i))
			reals[j].Value = buf
			reals[j].Time = t + int64(i)
		}

		db, err := op.DB()
		if err != nil {
			logs.Error(err)
			return
		}
		//_, err = db.Exec("Write Realtime", rows...)
		_, err = db.Exec("Write Archive", rows...)

		if err != nil {
			logs.Error(err)
			return
		}
		//time.Sleep(time.Second)
	}
}
